package com.simtop.beefsheepmaching.exception;

import com.simtop.beefsheepmaching.common.ServerResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author lvyognwei
 * @description  全局处理异常
 */
@RestControllerAdvice
public class GlobalExceptionHandle {

    private Logger log = LoggerFactory.getLogger(GlobalExceptionHandle.class);

    /**
     * exception异常处理
     * @return
     */
    @ExceptionHandler(Exception.class)
    public ServerResponse exceptionHandle(Exception e){
        log.error(e.getMessage(), e);
        return ServerResponse.createByErrorMsg("操作失败" + e.getMessage());
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(CustomException.class)
    public ServerResponse validatedBindException(CustomException e) {
        log.error(e.getMessage(), e);
        String message = e.getMessage();
        return ServerResponse.createByErrorMsg(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(BindException.class)
    public ServerResponse validatedBindException(BindException e) {
        log.error(e.getMessage(), e);
        String message = e.getAllErrors().get(0).getDefaultMessage();
        return ServerResponse.createByErrorMsg(message);
    }

    /**
     * 自定义验证异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ServerResponse validExceptionHandler(MethodArgumentNotValidException e) {
        log.error(e.getMessage(), e);
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return ServerResponse.createByErrorMsg(message);
    }
}